"""
插件权限控制系统
提供细粒度的权限控制和访问管理
"""

from typing import Dict, List, Set
from enum import Enum
import hashlib
import json


class Permission(Enum):
    """权限枚举"""
    # 文件系统权限
    FILE_READ = "file.read"
    FILE_WRITE = "file.write"
    FILE_EXECUTE = "file.execute"
    
    # 网络权限
    NETWORK_CONNECT = "network.connect"
    NETWORK_LISTEN = "network.listen"
    
    # 系统权限
    SYSTEM_PROCESS = "system.process"
    SYSTEM_REGISTRY = "system.registry"
    
    # UI权限
    UI_WINDOW = "ui.window"
    UI_DIALOG = "ui.dialog"
    
    # 数据权限
    DATA_READ = "data.read"
    DATA_WRITE = "data.write"


class PermissionManager:
    """权限管理器"""
    
    def __init__(self):
        self._plugin_permissions: Dict[str, Set[Permission]] = {}
        self._default_permissions: Set[Permission] = {
            Permission.FILE_READ,
            Permission.DATA_READ
        }
    
    def grant_permission(self, plugin_name: str, permission: Permission) -> None:
        """授予插件权限"""
        if plugin_name not in self._plugin_permissions:
            self._plugin_permissions[plugin_name] = set()
        self._plugin_permissions[plugin_name].add(permission)
    
    def revoke_permission(self, plugin_name: str, permission: Permission) -> None:
        """撤销插件权限"""
        if plugin_name in self._plugin_permissions:
            self._plugin_permissions[plugin_name].discard(permission)
    
    def check_permission(self, plugin_name: str, permission: Permission) -> bool:
        """检查插件是否具有指定权限"""
        # 检查插件特定权限
        if plugin_name in self._plugin_permissions:
            return permission in self._plugin_permissions[plugin_name]
        
        # 检查默认权限
        return permission in self._default_permissions
    
    def get_plugin_permissions(self, plugin_name: str) -> List[Permission]:
        """获取插件的所有权限"""
        if plugin_name in self._plugin_permissions:
            return list(self._plugin_permissions[plugin_name])
        return []
    
    def set_plugin_permissions(self, plugin_name: str, permissions: List[Permission]) -> None:
        """设置插件权限"""
        self._plugin_permissions[plugin_name] = set(permissions)


class AccessControl:
    """访问控制"""
    
    def __init__(self, permission_manager: PermissionManager):
        self._permission_manager = permission_manager
    
    def require_permission(self, plugin_name: str, permission: Permission):
        """装饰器：要求特定权限"""
        def decorator(func):
            def wrapper(*args, **kwargs):
                if not self._permission_manager.check_permission(plugin_name, permission):
                    raise PermissionError(f"Plugin '{plugin_name}' lacks permission: {permission.value}")
                return func(*args, **kwargs)
            return wrapper
        return decorator
    
    def check_access(self, plugin_name: str, permission: Permission) -> bool:
        """检查访问权限"""
        return self._permission_manager.check_permission(plugin_name, permission)